package com.java110.mall.cart.cmd.housekeeping;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.java110.core.annotation.Java110Cmd;
import com.java110.core.annotation.Java110Transactional;
import com.java110.core.context.CmdContextUtils;
import com.java110.core.context.ICmdDataFlowContext;
import com.java110.core.event.cmd.Cmd;
import com.java110.core.event.cmd.CmdEvent;
import com.java110.core.factory.GenerateCodeFactory;
import com.java110.dto.file.FileDto;
import com.java110.dto.file.FileRelDto;
import com.java110.dto.housekeeping.HousekeepingServPoolDto;
import com.java110.dto.housekeeping.HousekeepingServPoolUserDto;
import com.java110.dto.storeOrder.StoreOrderCartDto;
import com.java110.dto.user.UserDto;
import com.java110.intf.cart.*;
import com.java110.intf.system.IFileInnerServiceSMO;
import com.java110.intf.system.IFileRelInnerServiceSMO;
import com.java110.intf.user.IUserV1InnerServiceSMO;
import com.java110.po.file.FileRelPo;
import com.java110.po.housekeeping.HousekeepingServPoolPo;
import com.java110.po.housekeeping.HousekeepingServPoolUserPo;
import com.java110.po.storeOrder.StoreOrderCartPo;
import com.java110.po.storeOrder.StoreOrderCartFeePo;
import com.java110.utils.exception.CmdException;
import com.java110.utils.util.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.math.BigDecimal;
import java.util.List;

/**
 * 家政遍历
 */
@Java110Cmd(serviceCode = "housekeeping.servPoolFinish")
public class ServPoolFinishCmd extends Cmd {

    @Autowired
    private IHousekeepingServPoolUserInnerServiceSMO housekeepingServPoolUserInnerServiceSMOImpl;


    @Autowired
    private IHousekeepingServPoolInnerServiceSMO housekeepingServPoolInnerServiceSMOImpl;

    @Autowired
    private IUserV1InnerServiceSMO userInnerServiceSMOImpl;

    @Autowired
    private IStoreOrderCartInnerServiceSMO storeOrderCartInnerServiceSMOImpl;

    @Autowired
    private IStoreOrderCartEventInnerServiceSMO storeOrderCartEventInnerServiceSMOImpl;

    @Autowired
    private IFileInnerServiceSMO fileInnerServiceSMOImpl;

    @Autowired
    private IFileRelInnerServiceSMO fileRelInnerServiceSMOImpl;

    @Autowired
    private IStoreOrderCartFeeInnerServiceSMO storeOrderCartFeeInnerServiceSMOImpl;



    @Override
    public void validate(CmdEvent event, ICmdDataFlowContext context, JSONObject reqJson) throws CmdException {
        Assert.hasKeyAndValue(reqJson, "shopId", "商铺不能为空");
        Assert.hasKeyAndValue(reqJson, "poolId", "未包含工单信息");
        Assert.hasKeyAndValue(reqJson, "context", "未包含派单内容");
    }

    @Override
    @Java110Transactional
    public void doCmd(CmdEvent event, ICmdDataFlowContext context, JSONObject reqJson) throws CmdException {

        String userId = CmdContextUtils.getUserId(context);
        UserDto userDto = new UserDto();
        userDto.setUserId(userId);
        List<UserDto> userDtos = userInnerServiceSMOImpl.queryUsers(userDto);
        Assert.listOnlyOne(userDtos, "用户不存在");
        reqJson.put("userName", userDtos.get(0).getName());
        String userName = reqJson.getString("userName");
        //获取商品集合
        //判断当前用户是否有需要处理的订单
        HousekeepingServPoolUserDto housekeepingServPoolUserDto = new HousekeepingServPoolUserDto();
        housekeepingServPoolUserDto.setPoolId(reqJson.getString("poolId"));
        housekeepingServPoolUserDto.setShopId(reqJson.getString("shopId"));
        housekeepingServPoolUserDto.setState(HousekeepingServPoolUserDto.STATE_DOING);
        housekeepingServPoolUserDto.setStaffId(userId);
        List<HousekeepingServPoolUserDto> housekeepingServPoolUserDtos = housekeepingServPoolUserInnerServiceSMOImpl.queryHousekeepingServPoolUsers(housekeepingServPoolUserDto);
        if (ListUtil.isNull(housekeepingServPoolUserDtos)) {
            throw new CmdException("当前用户没有需要处理订单");
        }

        HousekeepingServPoolDto housekeepingServPoolDto = new HousekeepingServPoolDto();
        housekeepingServPoolDto.setPoolId(housekeepingServPoolUserDtos.get(0).getPoolId());
        housekeepingServPoolDto.setShopId(housekeepingServPoolUserDtos.get(0).getShopId());
        List<HousekeepingServPoolDto> housekeepingServPoolDtos = housekeepingServPoolInnerServiceSMOImpl.queryHousekeepingServPools(housekeepingServPoolDto);
        Assert.listOnlyOne(housekeepingServPoolDtos, "订单不存在");
        JSONArray fees = reqJson.getJSONArray("fees");
         double temPayPrice = _doSaveNewFees(reqJson, fees);
        // 1.0 关闭自己订单
        HousekeepingServPoolUserPo housekeepingServPoolUserPo = new HousekeepingServPoolUserPo();
        housekeepingServPoolUserPo.setRuId(housekeepingServPoolUserDtos.get(0).getRuId());
        housekeepingServPoolUserPo.setEndTime(DateUtil.getNow(DateUtil.DATE_FORMATE_STRING_A));
        housekeepingServPoolUserPo.setState(HousekeepingServPoolUserDto.STATE_CLOSE);
        housekeepingServPoolUserPo.setContext(reqJson.getString("context"));
        housekeepingServPoolUserPo.setShopId(reqJson.getString("shopId"));
        int flag = housekeepingServPoolUserInnerServiceSMOImpl.updateHousekeepingServPoolUser(housekeepingServPoolUserPo);
        if (flag < 1) {
            throw new IllegalArgumentException("关闭自己订单失败");
        }
        //将工单改为待支付状态
        HousekeepingServPoolPo housekeepingServPoolPo = new HousekeepingServPoolPo();
        StoreOrderCartPo storeOrderCartPo = new StoreOrderCartPo();
        if (!ListUtil.isNull(fees)) {
            //2.0 给开始节点派支付单
            housekeepingServPoolUserDto = new HousekeepingServPoolUserDto();
            housekeepingServPoolUserDto.setPoolId(reqJson.getString("poolId"));
            housekeepingServPoolUserDto.setShopId(reqJson.getString("shopId"));
            housekeepingServPoolUserDto.setPoolEvent(HousekeepingServPoolUserDto.POOL_EVENT_START_USER);
            housekeepingServPoolUserDtos = housekeepingServPoolUserInnerServiceSMOImpl.queryHousekeepingServPoolUsers(housekeepingServPoolUserDto);
            if (ListUtil.isNull(housekeepingServPoolUserDtos)) {
                throw new IllegalArgumentException("数据错误 该订单没有发起人！");
            }
            housekeepingServPoolUserPo = new HousekeepingServPoolUserPo();
            housekeepingServPoolUserPo.setRuId(GenerateCodeFactory.getGeneratorId(GenerateCodeFactory.CODE_PREFIX_ruId));
            housekeepingServPoolUserPo.setStartTime(DateUtil.getNow(DateUtil.DATE_FORMATE_STRING_A));
            housekeepingServPoolUserPo.setState(HousekeepingServPoolUserDto.STATE_PAY_FEE);
            housekeepingServPoolUserPo.setContext("待支付"+temPayPrice+"元");
            housekeepingServPoolUserPo.setPoolId(reqJson.getString("poolId"));
            housekeepingServPoolUserPo.setStaffId(housekeepingServPoolUserDtos.get(0).getStaffId());
            housekeepingServPoolUserPo.setStaffName(housekeepingServPoolUserDtos.get(0).getStaffName());
            housekeepingServPoolUserPo.setPreStaffId(userId);
            housekeepingServPoolUserPo.setPreStaffName(userName);
            housekeepingServPoolUserPo.setPreRuId(housekeepingServPoolUserDtos.get(0).getRuId());
            housekeepingServPoolUserPo.setPoolEvent(HousekeepingServPoolUserDto.POOL_EVENT_PAY_USER);
            housekeepingServPoolUserPo.setShopId(reqJson.getString("shopId"));
            flag = housekeepingServPoolUserInnerServiceSMOImpl.saveHousekeepingServPoolUser(housekeepingServPoolUserPo);
            if (flag < 1) {
                throw new IllegalArgumentException("保存待支付订单失败");
            }
            housekeepingServPoolPo.setState(HousekeepingServPoolDto.STATE_PAY);
            storeOrderCartPo.setState(StoreOrderCartDto.STATE_WAIT_SERV_WAIT_PAY);
        } else {
            housekeepingServPoolPo.setState(HousekeepingServPoolDto.STATE_COMPLATE);
            storeOrderCartPo.setState(StoreOrderCartDto.STATE_WAIT_REPAIR);
        }
        housekeepingServPoolPo.setShopId(housekeepingServPoolUserDtos.get(0).getShopId());
        housekeepingServPoolPo.setPoolId(housekeepingServPoolUserDtos.get(0).getPoolId());
        flag = housekeepingServPoolInnerServiceSMOImpl.updateHousekeepingServPool(housekeepingServPoolPo);
        if (flag < 1) {
            throw new IllegalArgumentException("保存待支付订单失败");
        }

        //修改购物车状态
        storeOrderCartPo.setCartId(housekeepingServPoolDtos.get(0).getCartId());
        storeOrderCartPo.setShopId(housekeepingServPoolDtos.get(0).getShopId());
        StoreOrderCartDto storeOrderCartDto = new StoreOrderCartDto();
        storeOrderCartDto.setCartId(storeOrderCartPo.getCartId());
        storeOrderCartDto.setShopId(storeOrderCartPo.getShopId());
        flag = storeOrderCartInnerServiceSMOImpl.updateStoreOrderCart(storeOrderCartPo);
        if (flag < 1) {
            throw new IllegalArgumentException("更新购物车失败");
        }
//        //处理派单数据
//        StoreOrderCartSendDto storeOrderCartSendDto = new StoreOrderCartSendDto();
//        storeOrderCartSendDto.setCartId( storeOrderCartPo.getCartId() );
//        storeOrderCartSendDto.setShopId( storeOrderCartPo.getShopId() );
//        List<StoreOrderCartSendDto> storeOrderCartSendDtos = storeOrderCartSendInnerServiceSMOImpl.queryStoreOrderCartSends( storeOrderCartSendDto );
//        if (storeOrderCartSendDtos == null && storeOrderCartSendDtos.size() < 1) {
//            throw new IllegalArgumentException("未查询到派单记录");
//        }
//        StoreOrderCartSendPo storeOrderCartSendPo = new StoreOrderCartSendPo();
//        storeOrderCartSendPo.setState( "1003" );
//        storeOrderCartSendPo.setFinishTime( DateUtil.getNow( DateUtil.DATE_FORMATE_STRING_A ) );
//        storeOrderCartSendPo.setSendId( storeOrderCartSendDtos.get( 0 ).getSendId() );
//        flag = storeOrderCartSendInnerServiceSMOImpl.updateStoreOrderCartSend( storeOrderCartSendPo );
//        if (flag < 1) {
//            throw new IllegalArgumentException( "修改派送状态失败" );
//        }
        List<StoreOrderCartDto> storeOrderCartDtos = storeOrderCartInnerServiceSMOImpl.queryStoreOrderCarts(storeOrderCartDto);
        if (ListUtil.isNull(storeOrderCartDtos)) {
            throw new IllegalArgumentException("没有查到购物车信息，请联系管理员");

        }

        //维修前图片处理
        if (reqJson.containsKey("beforeRepairPhotos") && !StringUtils.isEmpty(reqJson.getString("beforeRepairPhotos"))) {
            JSONArray beforeRepairPhotos = reqJson.getJSONArray("beforeRepairPhotos");
            for (int _photoIndex = 0; _photoIndex < beforeRepairPhotos.size(); _photoIndex++) {
                FileDto fileDto = new FileDto();
                fileDto.setFileId(GenerateCodeFactory.getGeneratorId(GenerateCodeFactory.CODE_PREFIX_file_id));
                fileDto.setFileName(fileDto.getFileId());
                fileDto.setContext(beforeRepairPhotos.getJSONObject(_photoIndex).getString("photo"));
                fileDto.setSuffix("jpeg");
                fileDto.setCommunityId(reqJson.getString("shopId"));
                String fileName = fileInnerServiceSMOImpl.saveFile(fileDto);
                reqJson.put("ownerPhotoId", fileDto.getFileId());
                reqJson.put("fileSaveName", fileName);
                JSONObject businessUnit = new JSONObject();
                businessUnit.put("fileRelId", GenerateCodeFactory.getGeneratorId(GenerateCodeFactory.CODE_PREFIX_file_id));
                businessUnit.put("relTypeCd", FileRelDto.BEFORE_REPAIR_PHOTOS);
                businessUnit.put("saveWay", "ftp");
                businessUnit.put("objId", reqJson.getString("poolId"));
                businessUnit.put("fileRealName", fileName);
                businessUnit.put("fileSaveName", fileName);
                FileRelPo fileRelPo = BeanConvertUtil.covertBean(businessUnit, FileRelPo.class);
                fileRelInnerServiceSMOImpl.saveFileRel(fileRelPo);
            }
        }
        //维修后图片处理
        if (reqJson.containsKey("afterRepairPhotos") && !StringUtils.isEmpty(reqJson.getString("afterRepairPhotos"))) {
            JSONArray afterRepairPhotos = reqJson.getJSONArray("afterRepairPhotos");
            for (int _photoIndex = 0; _photoIndex < afterRepairPhotos.size(); _photoIndex++) {
                FileDto fileDto = new FileDto();
                fileDto.setFileId(GenerateCodeFactory.getGeneratorId(GenerateCodeFactory.CODE_PREFIX_file_id));
                fileDto.setFileName(fileDto.getFileId());
                fileDto.setContext(afterRepairPhotos.getJSONObject(_photoIndex).getString("photo"));
                fileDto.setSuffix("jpeg");
                fileDto.setCommunityId(reqJson.getString("shopId"));
                String fileName = fileInnerServiceSMOImpl.saveFile(fileDto);
                reqJson.put("ownerFinishPhotoId", fileDto.getFileId());
                reqJson.put("fileFinishSaveName", fileName);
                JSONObject businessUnit = new JSONObject();
                businessUnit.put("fileRelId", GenerateCodeFactory.getGeneratorId(GenerateCodeFactory.CODE_PREFIX_file_id));
                businessUnit.put("relTypeCd", FileRelDto.AFTER_REPAIR_PHOTOS);
                businessUnit.put("saveWay", "ftp");
                businessUnit.put("objId", reqJson.getString("poolId"));
                businessUnit.put("fileRealName", fileName);
                businessUnit.put("fileSaveName", fileName);
                FileRelPo fileRelPo = BeanConvertUtil.covertBean(businessUnit, FileRelPo.class);
                fileRelInnerServiceSMOImpl.saveFileRel(fileRelPo);
            }
        }
    }

    private double _doSaveNewFees(JSONObject reqJson, JSONArray fees) {
        BigDecimal outPayPrice = new BigDecimal(0);
        if (ListUtil.isNull(fees)) {
            return outPayPrice.doubleValue();
        }

        //根据poolId 查询 cartId
        HousekeepingServPoolDto housekeepingServPoolDto = new HousekeepingServPoolDto();
        housekeepingServPoolDto.setPoolId(reqJson.getString("poolId"));
        housekeepingServPoolDto.setShopId(reqJson.getString("shopId"));
        List<HousekeepingServPoolDto> housekeepingServPoolDtos = housekeepingServPoolInnerServiceSMOImpl.queryHousekeepingServPools(housekeepingServPoolDto);
        String cartId = "";
        if (ListUtil.isNull(housekeepingServPoolDtos)) {
            cartId = GenerateCodeFactory.getGeneratorId(GenerateCodeFactory.CODE_PREFIX_cartId);
        } else {
            cartId = housekeepingServPoolDtos.get(0).getCartId();
        }
        JSONObject fee = null;
        for (int feeIndex = 0; feeIndex < fees.size(); feeIndex++) {
            fee = fees.getJSONObject(feeIndex);
            if (!StringUtil.isEmpty(fee.getString("checked")) && "false".equals(fee.getString("checked"))) {
                continue;
            }
            StoreOrderCartFeePo storeOrderCartFeePo = new StoreOrderCartFeePo();
            storeOrderCartFeePo.setDetailId(GenerateCodeFactory.getGeneratorId(GenerateCodeFactory.CODE_PREFIX_detailId));
            storeOrderCartFeePo.setCartId(cartId);
            storeOrderCartFeePo.setShopId(reqJson.getString("shopId"));
            storeOrderCartFeePo.setFeeConfigId(fee.getString("configId"));
            storeOrderCartFeePo.setFeeName(fee.getString("feeName"));
            storeOrderCartFeePo.setPrice(fee.getString("price"));
            storeOrderCartFeePo.setPayPrice(fee.getString("payPrice"));
            outPayPrice = outPayPrice.add(new BigDecimal(Double.parseDouble(fee.getString("payPrice")))).setScale(2, BigDecimal.ROUND_HALF_UP);

            storeOrderCartFeePo.setPayWay("-1");
            //1001 未支付、2002 已支付
            storeOrderCartFeePo.setState("1001");
            storeOrderCartFeePo.setExtOrderId("-1");
            storeOrderCartFeePo.setRemark("");
            storeOrderCartFeePo.setUpdateTime(DateUtil.getNow("yyyy-MM-dd HH:mm:ss"));
            int flag = storeOrderCartFeeInnerServiceSMOImpl.saveStoreOrderCartFee(storeOrderCartFeePo);
            if (flag < 1) {
                throw new IllegalArgumentException("订单费用失败");
            }
        }

        return outPayPrice.doubleValue();
    }
}
